package com.kbbywyclient.ui.activity;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.data.entity.CreditCardTableMenu;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.LoansTableMenu;
import com.kbbywyclient.data.entity.ResultInfoCre;
import com.kbbywyclient.data.entity.StatusUpdate;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.BoughtTableCreditModule;
import com.kbbywyclient.presenter.BoughtTableCrePresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.BoughtTableCreditAdapter;
import com.kbbywyclient.ui.adapter.MenuCreditCardAdapter;
import com.kbbywyclient.ui.adapter.MenuEducationAdapter;
import com.kbbywyclient.ui.adapter.MenuStatusAdapter;
import com.kbbywyclient.ui.adapter.MenuUnitPropertyAdapter;
import com.kbbywyclient.ui.contarct.BoughtTableCreditContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomPopwin;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.GetMoreListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Description: 已购买客户表单
 * Created by FHW
 * on 2017/4/17
 */

public class BoughtTableCreActivity extends BaseActivity implements BoughtTableCreditContract.View {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.ptr_view)
    PtrClassicFrameLayout ptr_view;
    @BindView(R.id.lv_bought_table_cre)
    GetMoreListView lv_bought_table_cre;

    @BindView(R.id.ll_view)
    LinearLayout ll_view;
    @BindView(R.id.ll_toolbar)
    LinearLayout ll_toolbar;
    @BindView(R.id.tv_card_holding)
    TextView tv_card_holding;
    @BindView(R.id.tv_culture)
    TextView tv_culture;
    @BindView(R.id.tv_info_provid)
    TextView tv_info_provid;
    @BindView(R.id.iv_card_holding)
    ImageView iv_card_holding;
    @BindView(R.id.iv_culture)
    ImageView iv_culture;
    @BindView(R.id.iv_info_provid)
    ImageView iv_info_provid;

    @Inject
    BoughtTableCrePresenter boughtTableCrePresenter;

    private String creditCard = "";
    private String dist = "";//城市区域ID
    private String education = "0";//学历ID
    //    private String personalInformation = "";//提供资料ID
    private String unitNature = "";//单位性质ID

    private BoughtTableCreditAdapter boughtTableCreditAdapter = null;

    private int mType = -1;

    private CustomPopwin popwin = null;

    private boolean isFirstLoad = true;

    private List<LoansTableMenu.CreditCardBean> creditCardBeanList = null;
    private MenuCreditCardAdapter menuCreditCardAdapter = null;

    private List<CreditCardTableMenu.EducationBean> educationBeanList = null;
    private MenuEducationAdapter menuEducationAdapter = null;

    //    private List<CreditCardTableMenu.PersonalInformationBean> personalInformationBeanList = null;
//    private MenuInformationAdapter menuInformationAdapter = null;
    private List<CreditCardTableMenu.UnitNatureBean> unitNatureBeanList = null;
    private MenuUnitPropertyAdapter menuUnitPropertyAdapter = null;

    private List<CreditCardTableMenu.StatusBean> statusBeanList = null;
    private MenuStatusAdapter menuStatusAdapter = null;

    private List<ResultInfoCre> resultInfoList = null;

    private CustomPopwin popwinModify = null;

    private int applyCreditCardID = -1;
    private String applyCreditCardSN = "";
    private String status = "";
    private String statusName = "";
    private int mPosition = 0;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_bought_table_credit;
    }

    @OnClick({R.id.ll_card_holding, R.id.ll_culture, R.id.ll_info_provid})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_card_holding://持卡情况
                mType = 0;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && creditCardBeanList.size() < 0) {
                    boughtTableCrePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
            case R.id.ll_culture://文化程度
                mType = 1;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && educationBeanList.size() < 0) {
                    boughtTableCrePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
            case R.id.ll_info_provid://资料提供
                mType = 2;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && unitNatureBeanList.size() < 0) {
                    boughtTableCrePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
        }
    }

    private void showPop(View view) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_customer_table, null, false);
        ListView lv_card_holding = (ListView) proView.findViewById(R.id.lv_card_holding);
        ListView lv_culture = (ListView) proView.findViewById(R.id.lv_culture);
        ListView lv_info_provid = (ListView) proView.findViewById(R.id.lv_info_provid);

        View v_dimess = proView.findViewById(R.id.v_dimess);

        lv_card_holding.setVisibility(View.GONE);
        lv_culture.setVisibility(View.GONE);
        lv_info_provid.setVisibility(View.GONE);

        if (popwin == null) {
            popwin = new CustomPopwin(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
        }
        switch (mType) {
            case 0:
                lv_card_holding.setVisibility(View.VISIBLE);
                if (creditCardBeanList != null) {
                    setCreditCardAdapter(lv_card_holding);
                }
                break;
            case 1:
                lv_culture.setVisibility(View.VISIBLE);
                if (educationBeanList != null) {
                    setEducationAdapter(lv_culture);
                }
                break;
            case 2:
                lv_info_provid.setVisibility(View.VISIBLE);
                if (unitNatureBeanList != null) {
                    setInformationAdapter(lv_info_provid);
                }
                break;
        }
        popwin.setFocusable(false);
        popwin.setContentView(proView);
        popwin.showAsDropDown(view, 0, 0);

        popwin.setOnDismissListener(() -> {
            setTextType();
        });
        lv_card_holding.setOnItemClickListener((parent, view13, position, id) -> {
            popwin.dismiss();
            for (int i = 0; i < creditCardBeanList.size(); i++) {
                creditCardBeanList.get(i).setCheck(false);
                if (position == i) {
                    creditCardBeanList.get(i).setCheck(true);
                    creditCard = creditCardBeanList.get(i).getCode();
                    ViewUtils.setText(tv_card_holding, creditCardBeanList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });

        lv_culture.setOnItemClickListener((parent, view1, position, id) -> {
            popwin.dismiss();
            for (int i = 0; i < educationBeanList.size(); i++) {
                educationBeanList.get(i).setCheck(false);
                if (position == i) {
                    educationBeanList.get(i).setCheck(true);
                    education = educationBeanList.get(i).getID() + "";
                    ViewUtils.setText(tv_culture, educationBeanList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });
        lv_info_provid.setOnItemClickListener((parent, view12, position, id) -> {
            popwin.dismiss();
//            for (int i = 0; i < personalInformationBeanList.size(); i++) {
//                personalInformationBeanList.get(i).setCheck(false);
//                if (position == i) {
//                    personalInformationBeanList.get(i).setCheck(true);
//                    personalInformation = personalInformationBeanList.get(i).getCode();
//                    ViewUtils.setText(tv_info_provid, personalInformationBeanList.get(i).getName());
//                }
//            }
            for (int i = 0; i < unitNatureBeanList.size(); i++) {
                unitNatureBeanList.get(i).setCheck(false);
                if (position == i) {
                    unitNatureBeanList.get(i).setCheck(true);
                    unitNature = unitNatureBeanList.get(i).getID() + "";
                    ViewUtils.setText(tv_info_provid, unitNatureBeanList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });

        v_dimess.setOnClickListener(v -> popwin.dismiss());

    }

    private void setCreditCardAdapter(ListView lv) {
        menuCreditCardAdapter = new MenuCreditCardAdapter(this, R.layout.item_menu_purpose, creditCardBeanList);
        lv.setAdapter(menuCreditCardAdapter);
    }

    private void setEducationAdapter(ListView lv) {
        menuEducationAdapter = new MenuEducationAdapter(this, R.layout.item_menu_purpose, educationBeanList);
        lv.setAdapter(menuEducationAdapter);
    }

    private void setInformationAdapter(ListView lv) {
//        menuInformationAdapter = new MenuInformationAdapter(this, R.layout.item_menu_purpose, personalInformationBeanList);
//        lv.setAdapter(menuInformationAdapter);
        menuUnitPropertyAdapter = new MenuUnitPropertyAdapter(this, R.layout.item_menu_purpose, unitNatureBeanList);
        lv.setAdapter(menuUnitPropertyAdapter);
    }

    private void showView(int type) {
        setTextType();
        switch (type) {
            case 0:
                tv_card_holding.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_card_holding.setBackgroundResource(R.mipmap.icon_table_up);
                break;
            case 1:
                tv_culture.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_culture.setBackgroundResource(R.mipmap.icon_table_up);
                break;
            case 2:
                tv_info_provid.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_info_provid.setBackgroundResource(R.mipmap.icon_table_up);
                break;
        }
    }

    private void setTextType() {
        tv_card_holding.setTextColor(getResources().getColor(R.color.color_212121));
        tv_culture.setTextColor(getResources().getColor(R.color.color_212121));
        tv_info_provid.setTextColor(getResources().getColor(R.color.color_212121));
        iv_card_holding.setBackgroundResource(R.mipmap.icon_table_dwon);
        iv_culture.setBackgroundResource(R.mipmap.icon_table_dwon);
        iv_info_provid.setBackgroundResource(R.mipmap.icon_table_dwon);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("信用卡-已购买客户表");
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);

        resultInfoList = new ArrayList<>();

        creditCardBeanList = new ArrayList<>();
        educationBeanList = new ArrayList<>();
//        personalInformationBeanList = new ArrayList<>();
        unitNatureBeanList = new ArrayList<>();
        statusBeanList = new ArrayList<>();

        v_toolbar.setLeftViewOnClickLinster(v -> finish());

        //加载更多
        lv_bought_table_cre.setOnGetMoreListener(() -> {
            refresh(false);
        });
        lv_bought_table_cre.setOnItemClickListener((parent, view, position, id) -> {
            if (position < resultInfoList.size() && resultInfoList.size() > 0) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("ApplyCreditCardID", resultInfoList.get(position).getApplyCreditCardID());
                map.put("ApplyCreditCardSN", resultInfoList.get(position).getApplyCreditCardSN());
                map.put("position", position);
                ActivitySkipUtil.skipAnotherActivity(this, CreditTableDetailActivity.class, map);
            }
        });

        lv_bought_table_cre.setOnSileListener(new GetMoreListView.OnSileListener() {
            @Override
            public void onSlideUp(int direction) {
                ll_view.setVisibility(View.GONE);
                ViewUtils.setViewAnim(direction, ll_toolbar);
            }

            @Override
            public void onSlideDwon(int direction) {
                ll_view.setVisibility(View.INVISIBLE);
                ViewUtils.setViewAnim(direction, ll_toolbar);
            }
        });

    }

    @Override
    public void initData() {
        ptr_view.setLastUpdateTimeRelateObject(this);
        ptr_view.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                lv_bought_table_cre.setHasMore();
                refresh(true);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        // the following are default settings
        ptr_view.setResistance(1.7f);
        ptr_view.setRatioOfHeaderHeightToRefresh(1.2f);
        ptr_view.postDelayed(() -> ptr_view.autoRefresh(), 100);
    }

    private void refresh(boolean isClean) {
        boughtTableCrePresenter.getCreditCardBuyOrders(isClean, PreUtils.getUser(this).getSalesID() + ""
                , dist, education, unitNature, creditCard);
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getBoughtTableCreditComponent(new BoughtTableCreditModule(this)).inject(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.BoughtMobile boughtMobile) {
        setScreenAction("通信", "信用卡-已购买客户-拨打电话");
    }

    /**
     * 修改 回调
     *
     * @param creditCardModify
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.CreditCardModify creditCardModify) {

        applyCreditCardID = resultInfoList.get(creditCardModify.getPosition()).getApplyCreditCardID();
        applyCreditCardSN = resultInfoList.get(creditCardModify.getPosition()).getApplyCreditCardSN();
        mPosition = creditCardModify.getPosition();

        for (CreditCardTableMenu.StatusBean statusBean : statusBeanList) {
            statusBean.setCheck(false);
            if (resultInfoList.get(creditCardModify.getPosition()).getStatus().equals(statusBean.getCode())) {
                statusBean.setCheck(true);
            }
        }
        showPopModify();
    }

    private void showPopModify() {

        status = "";
        statusName = "";

        View proView = LayoutInflater.from(this).inflate(R.layout.pop_status_modify, null, false);

        ImageView iv_colse = (ImageView) proView.findViewById(R.id.iv_colse);
        ListView lv_status = (ListView) proView.findViewById(R.id.lv_status);
        TextView tv_determine = (TextView) proView.findViewById(R.id.tv_determine);

        if (popwinModify == null) {
            popwinModify = new CustomPopwin(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.6f);
        }

        if (statusBeanList != null) {
            setStatusAdapter(lv_status);
        }

        popwinModify.setContentView(proView);
        popwinModify.showAtLocation(proView, Gravity.CENTER, 0, 0);

        iv_colse.setOnClickListener(onListtener);
        tv_determine.setOnClickListener(onListtener);

        lv_status.setOnItemClickListener((parent, view, position, id) -> {
            for (int i = 0; i < statusBeanList.size(); i++) {
                statusBeanList.get(i).setCheck(false);
                if (position == i) {
                    statusBeanList.get(i).setCheck(true);
                    status = statusBeanList.get(i).getCode();
                    statusName = statusBeanList.get(i).getName();
                    menuStatusAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    private void setStatusAdapter(ListView lv_status) {
        menuStatusAdapter = new MenuStatusAdapter(this, R.layout.item_menu_status_credit, statusBeanList);
        lv_status.setAdapter(menuStatusAdapter);
    }

    private View.OnClickListener onListtener = v -> {
        switch (v.getId()) {
            case R.id.iv_colse:
                popwinModify.dismiss();
                break;
            case R.id.tv_determine:
                popwinModify.dismiss();

                if (StringUtil.isNotEmpty(status)) {
                    boughtTableCrePresenter.getapplyCreditCardUpdate(PreUtils.getUser(this).getSalesID() + ""
                            , applyCreditCardID + "", applyCreditCardSN, status, "");
                }

                break;
        }
    };

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void loadSucBoughtTableCre(List<ResultInfoCre> resultInfoList) {
        ptr_view.refreshComplete();
        if (isFirstLoad) {
            ll_view.setVisibility(View.INVISIBLE);
            boughtTableCrePresenter.getCreditCardMenu(PreUtils.getUser(this).getSalesID() + "");
        }
    }

    @Override
    public void loadFaiBoughtTableCre(String errorMsg) {
        ptr_view.refreshComplete();
        lv_bought_table_cre.getMoreComplete();
    }

    @Override
    public void setAdapterOrNotify(List<ResultInfoCre> mResultInfoList) {
        if (resultInfoList.size() > 0) {
            resultInfoList.clear();
        }
        resultInfoList.addAll(mResultInfoList);
        if (boughtTableCreditAdapter == null) {
            boughtTableCreditAdapter = new BoughtTableCreditAdapter(this, R.layout.item_bought_credit_table, resultInfoList);
            lv_bought_table_cre.setAdapter(boughtTableCreditAdapter);
        } else {
            boughtTableCreditAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setNoMore() {
        lv_bought_table_cre.setNoMore();
    }

    @Override
    public void setMoreComplete() {
        lv_bought_table_cre.getMoreComplete();
    }

    @Override
    public void loadSucMenu(CreditCardTableMenu creditCardTableMenu) {
        LoansTableMenu.CreditCardBean creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("不限");
        creditCardBean.setCode("");
        creditCardBean.setCheck(true);
        creditCardBeanList.add(creditCardBean);
        creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("无信用卡");
        creditCardBean.setCode("0");
        creditCardBeanList.add(creditCardBean);
        creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("持有信用卡");
        creditCardBean.setCode("1");
        creditCardBeanList.add(creditCardBean);

        educationBeanList.addAll(creditCardTableMenu.getEducation());
        CreditCardTableMenu.EducationBean educationBean = new CreditCardTableMenu.EducationBean();
        educationBean.setName("不限");
        educationBean.setCheck(true);
        educationBeanList.add(0, educationBean);

        unitNatureBeanList.addAll(creditCardTableMenu.getUnitNature());
        CreditCardTableMenu.UnitNatureBean unitNatureBean = new CreditCardTableMenu.UnitNatureBean();
        unitNatureBean.setName("不限");
        unitNatureBean.setCheck(true);
        unitNatureBeanList.add(0, unitNatureBean);

        statusBeanList.addAll(creditCardTableMenu.getStatus());


        if (!isFirstLoad) {
            showPop(ll_toolbar);
        }
        isFirstLoad = false;
    }

    @Override
    public void loadFaiMenu(String errorMsg) {

    }

    @Override
    public void loadSucCreditCardUpdate(StatusUpdate statusUpdate) {
        resultInfoList.get(mPosition).setStatus(status);
        resultInfoList.get(mPosition).setStatusName(statusName);
        boughtTableCreditAdapter.notifyDataSetChanged();
    }

    @Override
    public void loadFaiCreditCardUpdate(String errorMsg) {

    }

}
